package com.aegis.manage.config;

import cn.hutool.core.collection.CollectionUtil;
import com.aegis.core.enums.AegisHttpMethod;
import com.aegis.core.model.AegisUserApi;
import com.aegis.core.model.AegisAppGroupPermission;
import com.aegis.manage.api.dto.RolePermissionDTO;
import com.aegis.manage.service.sys.permission.SysPermissionService;
import com.aegis.spring.AegisInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
@Configuration
public class ManagerConfiguration {

    @Autowired
    private ManageProperties manageProperties;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Bean
    @DependsOn("scheduleTaskService")
    public AegisInitializer aegisInitializer() {
        List<RolePermissionDTO> rolePermissionDTOS = sysPermissionService.selectRolePermissionByRoleId(null);
        return new AegisInitializer()
                .initGroupPermission(rolePermissionDTOS.stream().map(rolePermissionDTO -> {
                    AegisAppGroupPermission aegisAppGroupPermission = new AegisAppGroupPermission();
                    aegisAppGroupPermission.setGroupKey(rolePermissionDTO.getRoleKey());
                    aegisAppGroupPermission.setGroupName(rolePermissionDTO.getRoleName());
                    aegisAppGroupPermission.setGroupId(rolePermissionDTO.getId());
                    List<String> adminRoles = manageProperties.getAdminRoles();
                    if (CollectionUtil.isNotEmpty(adminRoles) && adminRoles.contains(rolePermissionDTO.getRoleKey())) {
                        AegisUserApi aegisUserApi = new AegisUserApi();
                        aegisUserApi.setApi("/**");
                        aegisUserApi.setName("超管权限");
                        aegisUserApi.setMethod(AegisHttpMethod.ALL);
                        aegisAppGroupPermission.setApis(List.of(aegisUserApi));
                    } else {
                        aegisAppGroupPermission.setApis(rolePermissionDTO.getPermissions().stream().map(sysPermissionDTO -> {
                            AegisUserApi aegisUserApi = new AegisUserApi();
                            aegisUserApi.setApi(sysPermissionDTO.getApi());
                            aegisUserApi.setName(sysPermissionDTO.getName());
                            aegisUserApi.setMethod(AegisHttpMethod.toEnum(sysPermissionDTO.getMethod()));
                            return aegisUserApi;
                        }).collect(Collectors.toList()));
                    }

                    return aegisAppGroupPermission;
                }).collect(Collectors.toList()));
    }


}
